package com.zz.inventory.controller;

import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.util.Random;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.api.domain.SysDept;
import com.zz.inventory.domain.SysUser;
import com.zz.inventory.domain.SysUserRole;
import com.zz.inventory.domain.SystemLogs;
import com.zz.inventory.service.*;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.zz.inventory.domain.Schools;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 学校信息管理Controller
 * 
 * @author zz
 * @date 2025-06-30
 */
@RestController
@RequestMapping("/schools")
public class SchoolsController extends BaseController
{
    @Autowired
    private ISchoolsService schoolsService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private ISysUserRoleService iSysUserRoleService;

    @Autowired
    private ISystemLogsService iSystemLogsService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysUserService userService;


    /**
     * 查询学校信息管理列表
     */
    @RequiresPermissions("platform:schools:list")
    @GetMapping("/list")
    public TableDataInfo list(Schools schools)
    {
        startPage();
        List<Schools> list = schoolsService.selectSchoolsList(schools);
        return getDataTable(list);
    }

    /**
     * 导出学校信息管理列表
     */
    @RequiresPermissions("platform:schools:export")
    @Log(title = "学校信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Schools schools)
    {
        List<Schools> list = schoolsService.selectSchoolsList(schools);
        ExcelUtil<Schools> util = new ExcelUtil<Schools>(Schools.class);
        util.exportExcel(response, list, "学校信息管理数据");
    }

    /**
     * 获取学校信息管理详细信息
     */
    @RequiresPermissions("platform:schools:query")
    @GetMapping(value = "/{schoolId}")
    public AjaxResult getInfo(@PathVariable("schoolId") Long schoolId)
    {
        return success(schoolsService.selectSchoolsBySchoolId(schoolId));
    }

    /**
     * 新增学校信息管理
     */
    @CrossOrigin("*")
//    @RequiresPermissions("platform:schools:add")
    @Log(title = "学校信息管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Schools schools) {
        schools.setStatus("待审核");
        return toAjax(schoolsService.insertSchools(schools));
    }

    /**
     * 修改学校信息管理
     */
    @Transactional
    @RequiresPermissions("platform:schools:edit")
    @Log(title = "学校信息管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Schools schools) {
        try {
            if ("活跃".equals(schools.getStatus())) {
                // 1. 更新学校信息
                int result = schoolsService.updateSchools(schools);
                if (result > 0) {
                    // 2. 处理部门树并获取部门ID
                    Long deptId = handleDeptTree(schools);
                    // 3. 创建管理员账号
                    createSchoolAdminUser(schools, deptId);
                }
                return success("操作成功");
            }
            return toAjax(schoolsService.updateSchools(schools));
        } catch (Exception e) {
            return error("操作失败: " + e.getMessage());
        }
    }

    private Long handleDeptTree(Schools school) {
        // 1. 提取城市名（取地址前3个字作为城市名）
        String address = school.getAddress();
        if (StringUtils.isBlank(address) || address.length() < 3) {
            throw new ServiceException("学校地址不完整");
        }
        String cityName = address.substring(0, 3);

        // 2. 查询或创建城市节点
        SysDept cityDept = deptService.selectDeptByNameAndParentId(cityName, 100L);
        if (cityDept == null) {
            cityDept = new SysDept();
            cityDept.setParentId(100L);
            cityDept.setAncestors("0,100");
            cityDept.setDeptName(cityName);
            cityDept.setOrderNum(0);
            cityDept.setStatus("0");
            deptService.insertDept(cityDept);

            // 更新ancestors
            cityDept.setAncestors("0,100," + cityDept.getDeptId());
            deptService.updateDept(cityDept);
        }

        // 3. 创建学校部门节点
        SysDept schoolDept = new SysDept();
        schoolDept.setParentId(cityDept.getDeptId());
        schoolDept.setAncestors(cityDept.getAncestors());
        schoolDept.setDeptName(school.getSchoolName());
        schoolDept.setOrderNum(0);
        schoolDept.setStatus("0");
        deptService.insertDept(schoolDept);

        return schoolDept.getDeptId(); // 返回新创建的部门ID
    }
    private Long getCityDeptId(String address) {
        if (StringUtils.isBlank(address) || address.length() < 3) {
            throw new ServiceException("学校地址不完整");
        }
        String cityName = address.substring(0, 3);
        SysDept cityDept = deptService.selectDeptByNameAndParentId(cityName, 100L);
        if (cityDept == null) {
            throw new ServiceException("城市部门不存在");
        }
        return cityDept.getDeptId();
    }
    private void createSchoolAdminUser(Schools schools,Long deptId) {
        // 3. 创建用户并设置deptId
        String username = "xx" + schools.getSchoolId();
        String password = "$2a$10$73B72oyubVSZVUI0rEqK/.VqGQZTH.ulu3dHoiBE8ByOhJIrdAu2";
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(schools.getContactPerson());
        sysUser.setUserType("00");
        sysUser.setEmail(schools.getEmail());
        sysUser.setPhonenumber(schools.getContactPhone());
        sysUser.setPassword(password);
        sysUser.setSchoolsId(schools.getSchoolId());
        sysUser.setStatus("0");
        sysUser.setCreateTime(new Date());
        sysUser.setRemark("学校管理员");
        sysUser.setDeptId(deptId); // 设置部门ID

        userService.insertSysUser(sysUser);
        associateUserWithRole(sysUser.getUserId(), 4L);

        SystemLogs systemLogs = new SystemLogs();
        systemLogs.setLogLevel("INFO");
        systemLogs.setSourceModule("平台管理");
        systemLogs.setSchoolId(schools.getSchoolId());     //学校ID
        systemLogs.setUserId(sysUser.getUserId());
        systemLogs.setAction("生成学校账号成功");
        try {
            iSystemLogsService.insertSystemLogs(systemLogs);
        } catch (Exception e) {
            // 打印详细异常栈，辅助排查
            e.printStackTrace();
            systemLogs.setLogLevel("DEBUG");
            systemLogs.setSourceModule("平台管理");
            systemLogs.setSchoolId(schools.getSchoolId());     //学校ID
            systemLogs.setUserId(sysUser.getUserId());
            systemLogs.setAction("生成学校账号失败");
            iSystemLogsService.insertSystemLogs(systemLogs);
            throw new RuntimeException("插入系统日志失败", e);
        }
    }

    private void associateUserWithRole(Long userId, Long roleId) {
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(userId);
        sysUserRole.setRoleId(roleId);
        iSysUserRoleService.insertSysUserRole(sysUserRole);
    }




    /**
     * 删除学校信息管理
     */
    @RequiresPermissions("platform:schools:remove")
    @Log(title = "学校信息管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{schoolIds}")
    public AjaxResult remove(@PathVariable Long[] schoolIds)
    {
        return toAjax(schoolsService.deleteSchoolsBySchoolIds(schoolIds));
    }

    @GetMapping("/{schoolId}/users")
    public TableDataInfo getSchoolUsers(@PathVariable Long schoolId) {
        startPage();
        List<SysUser> list = userService.selectUsersBySchoolId(schoolId);
        return getDataTable(list);
    }

}
